namespace AutoTLBB
{
    using System;
    using System.Diagnostics;
    using System.Runtime.InteropServices;

    public class ShutDownPC
    {
        [return: MarshalAs(UnmanagedType.Bool)]
        [DllImport("advapi32.dll", SetLastError=true)]
        private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
        [DllImport("user32.dll", SetLastError=true)]
        private static extern int ExitWindowsEx(uint uFlags, uint dwReason);
        [DllImport("advapi32.dll")]
        private static extern int LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
        [DllImport("advapi32.dll")]
        private static extern int OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, out IntPtr TokenHandle);
		/// <summary>
		/// Shutdown2s this instance.
		/// </summary>
        public static void Shutdown2()
        {
            IntPtr ptr;
            TOKEN_PRIVILEGES token_privileges;
            OpenProcessToken(Process.GetCurrentProcess().Handle, 40, out ptr);
            token_privileges.PrivilegeCount = 1;
            token_privileges.Privileges.Attributes = 2;
            LookupPrivilegeValue("", "SeShutdownPrivilege", out token_privileges.Privileges.pLuid);
            AdjustTokenPrivileges(ptr, false, ref token_privileges, 0, IntPtr.Zero, IntPtr.Zero);
            ExitWindowsEx(1, 0);
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct LUID
        {
            public int LowPart;
            public int HighPart;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct LUID_AND_ATTRIBUTES
        {
            public ShutDownPC.LUID pLuid;
            public int Attributes;
        }

        [StructLayout(LayoutKind.Sequential)]
        private struct TOKEN_PRIVILEGES
        {
            public int PrivilegeCount;
            public ShutDownPC.LUID_AND_ATTRIBUTES Privileges;
        }
    }
}

